﻿// Copyright (C) 2009  Lex Li
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.

using System;
using System.IO;
using System.Windows.Forms;

using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using Lextm.M8Pack.ThemeBuilder.Properties;

namespace Lextm.M8Pack.ThemeBuilder
{
	internal class ThemeBuilder
	{
		private readonly string _root;
		private Theme _current;
		private readonly FastZip _zipper = new FastZip();

		public ThemeBuilder(string root)
		{
			_root = Path.Combine(root, "M8ThemeBuilder");
		}
		
		private string WorkingFolder
		{
			get { return Path.Combine(_root, "working"); }
		}
		
		private string PackageFolder
		{
			get { return Path.Combine(_root, "package"); }
		}
		
		public Theme Theme
		{
			get { return _current; }
		}

        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")]
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Globalization", "CA1300:SpecifyMessageBoxOptions")]
		public void LoadTheme(string fileName)
		{
			if (fileName == null)
			{
				throw new ArgumentNullException("fileName");
			}
			
			if (Directory.Exists(PackageFolder))
			{
				Directory.Delete(PackageFolder, true); // IMPORTANT: clear the temp folder.
			}

			bool extracted = true;
			try
			{
				_zipper.ExtractZip(fileName, PackageFolder, string.Empty);
			}
			catch (SharpZipBaseException)
			{
				extracted = false;
			}

			if (!extracted)
			{
				MessageBox.Show(Resources.MthDecompressionError);
				return;
			}

			string cfg = Path.Combine(PackageFolder, Resources.CfgFileName);
			if (!File.Exists(cfg))
			{
				MessageBox.Show(Resources.CfgMissingError);
				return;
			}

			_current = new Theme(cfg, PackageFolder, WorkingFolder);
		}
		
		public void SaveTheme(string fileName)
		{
			if (fileName == null)
			{
				throw new ArgumentNullException("fileName");
			}
			
			_current.Persist();
			string temp = Path.GetTempFileName();
			_zipper.CreateZip(temp, WorkingFolder, false, string.Empty);
			File.Copy(temp, fileName, true);
		}
	}
}
